package com.atguigu.chapter05.sink;

import com.alibaba.fastjson.JSON;
import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;

import java.util.ArrayList;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/6/10 10:09
 */
public class Flink01_Sink_Kafka {
    public static void main(String[] args) throws Exception {
        ArrayList<WaterSensor> waterSensors = new ArrayList<>();
        waterSensors.add(new WaterSensor("sensor_1", 1607527992000L, 20));
        waterSensors.add(new WaterSensor("sensor_1", 1607527994000L, 50));
        waterSensors.add(new WaterSensor("sensor_1", 1607527996000L, 50));
        waterSensors.add(new WaterSensor("sensor_2", 1607527993000L, 10));
        waterSensors.add(new WaterSensor("sensor_2", 1607527995000L, 30));
        
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);
        
        env
            .fromCollection(waterSensors)
            .map(JSON::toJSONString)
            .addSink(new FlinkKafkaProducer<String>(
                "hadoop162:9092",
                "sensor",
                new SimpleStringSchema()
            ));
        
        env.execute();
        
    }
}
/*
0. 当并行度小于分区数的时候, 会导致kafka的个别分区数据

1. 当向kafka写数据的时候, 让你的并行度和kafka的分区保持一致.

2. 也可以采用轮询的方式写入, 或者让kafka根据key自动计算分区索引

 */